import baseURL from './config.js'
export default {
	config:{
		baseURL:baseURL.baseUrl,
		// 请求拦截器
		beforeRequest(options = {}){
			return new Promise((resolve,reject)=>{
				// 公共参数处理
				options.url = this.baseURL + options.url 
				options.method = options.method || 'GET'
				options.header = {
 					Authorization:"Bearer 6734020203d24eb8995ac03fc82fbd71"
				}
				resolve(options)
			})
		},
		// 响应拦截器
		handleResponse(res){
			console.log(res,'res')
			return new Promise((resolve,reject)=>{
				if(res.data.code == "10000"){
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					});
				}
				
				resolve(res.data)
			})
		}
	},
	request(options = {}){
		return this.config.beforeRequest(options).then(opt=>uni.request(opt)).then(res => this.config.handleResponse(res))
	},
	// GET请求
	get(url,params = null,options = {}){
		options.url = url
		
		options.url += params ? ('?'+Object.keys(params).map(key=>key+'='+params[key]).join('&')) : ''
		
		options.method = 'GET'
		return this.request(options)
	},
	// POST请求
	post(url,data = {},options = {}){
		options.url = url
		options.method = 'POST'
		options.data = data
		return this.request(options)
	},
	// 上传文件
	upload(url,data = {},options = {}){
		options.url = url
		return this.config.beforeRequest(options).then(opt=>{
			return new Promise((resolve,reject)=>{
				let uploadTask = uni.uploadFile({
					url:opt.url, 
					filePath: data.filePath,
					name: data.name || 'file',
					header:opt.header,
					success: (res) => {
						// setTimeout(() => {
						// 	let json = JSON.parse(res.data);
						// 	uni.hideLoading();
						// 	resolve(json.data.result.address);
						// }, 1000);
						// console.log(res,'res')
						// if(res.statusCode != 200){
						// 	reject('上传失败')
						// 	return uni.showToast({
						// 		title: '上传失败',
						// 		icon: 'none'
						// 	});
						// }
						// let message = JSON.parse(res.data)
						resolve(res)
					},
					fail: (err) => {
						uni.hideLoading();
					}
				});
				
				uploadTask.onProgressUpdate((res) => {
					if(options.onProgress && typeof options.onProgress == 'function'){
						options.onProgress(res.progress)
					}
				});
			})
		})
	}
}